package com.gzgy.ustore.api.service.impl;

import com.gzgy.ustore.api.common.exception.BaseAPIException;
import com.gzgy.ustore.api.common.exception.ExceptionCodeStatusEnum;
import com.gzgy.ustore.api.common.util.Constant;
import com.gzgy.ustore.api.common.util.DateUtil;
import com.gzgy.ustore.api.common.util.I18nUtil;
import com.gzgy.ustore.api.dao.UserDao;
import com.gzgy.ustore.api.dao.UserRoleDao;
import com.gzgy.ustore.api.dao.UserSessionDao;
import com.gzgy.ustore.api.model.UserListModel;
import com.gzgy.ustore.api.model.UserModel;
import com.gzgy.ustore.api.service.RoleService;
import com.gzgy.ustore.api.service.UserService;
import com.ustore.model.Roles;
import com.ustore.model.User;
import com.ustore.model.UserRole;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private UserSessionDao userSessionDao;

    @Autowired
    private RoleService roleService;

    @Override
    public UserModel loginWebPage(String userCode, String userPwd, String companyId) {

        Map<String, Object> map = new HashMap<String, Object>();

        //从数据库查找 用户信息
        UserModel user = userDao.loginWebPage(userCode, userPwd, companyId);
        if (user == null) {
            Integer errorCode = ExceptionCodeStatusEnum.USER_NOT_FOUND_EXCEPTION.toInt();
            throw new BaseAPIException(I18nUtil.getMessage(errorCode, null, "zh_CN"), errorCode);
        }
        //给用户新增session
        String session = Constant.getUUID();
        Integer result = userSessionDao.addUserSession(NumberUtils.toInt(user.getUserId().toString()), session);
        if (result <= 0) {
            throw new BaseAPIException("登陆失败");
        } else {
            user.setSession(session);
        }
        return user;
    }

    @Override
    public Map<String, Object> getUserList(String companyId, String index, String page) {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取role list
        List<Roles> rolesList = roleService.getRoleList();
        int count = 0;
        count = userDao.userCount(companyId);
        map.put("count", count);
        map.put("userList", new ArrayList<UserListModel>());
        if (count > 0) {
            List<UserListModel> list = userDao.getUserList(companyId, NumberUtils.toInt(index), NumberUtils.toInt(page));
            for (UserListModel l : list) {
                StringBuffer roleName = new StringBuffer();
                String[] roles = l.getRoleId().split(",");
                for (String s : roles) {
                    for (Roles r : rolesList) {
                        if (s.equals(r.getId().toString())) {
                            roleName.append(r.getRoleName() + ",");
                        }
                    }
                    l.setRoleNames(roleName.substring(0, roleName.length() - 1));
                }
            }
            map.put("userList", list);
        }
        map.put("index", index);

        return map;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public String addUser(String userCode, String userName, String userPwd, String companyId, String orgId, String roleId, String email, String phone, String userId) {

        //首先 从数据库找到 存不存在这个用户，没有新增
        int foundUser = userDao.userCount(companyId, userCode);
        if (foundUser > 0) {
            int errorCode = ExceptionCodeStatusEnum.USER_IS_EXISTS_EXCEPTION.toInt();
            String errorMsg = I18nUtil.getMessage(errorCode, null, "zh_CN");
            throw new BaseAPIException(errorMsg, errorCode);
        }
        //新增用户
        User user = new User();
        user.setEmail(email);
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setCompanyId(NumberUtils.toInt(companyId));
        user.setOrgId(orgId);
        user.setPhone(phone);
        user.setUserPwd(userPwd);
        user.setCreatedBy(userId);
        user.setCreatedTime(DateUtil.getCurrentDate());

        Object id = userDao.add(user).getId();

        //添加 用户 role 关系
        UserRole userRole = new UserRole();
        userRole.setCompanyId(NumberUtils.toInt(companyId));
        userRole.setRoleId(roleId);
        userRole.setUserId(NumberUtils.toInt(id.toString()));
        userRole.setCreatedBy(userId);
        userRole.setCreatedTime(DateUtil.getCurrentDate());

        userRoleDao.add(userRole);

        return id.toString();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public String userOperation(String flag, String uId, String userId, String userName, String orgId, String roleId, String email, String phone) throws SQLException {
        //0 更新 数据
        //1 删除 数据
        if ("0".equals(flag)) {
            User user = userDao.get(uId);
            if (user == null) {
                int errorCode = ExceptionCodeStatusEnum.USER_NOT_FOUND_EXCEPTION.toInt();
                String errorMsg = I18nUtil.getMessage(errorCode, null, "zh_CN");
                throw new BaseAPIException(errorMsg, errorCode);
            }
            user.setEmail(email);
            user.setPhone(phone);
            user.setUserName(userName);
            user.setOrgId(orgId);
            user.setUpdatedBy(userId);
            user.setUpdatedTime(DateUtil.getCurrentDate());
            userDao.update(user);

            UserRole userRole = userRoleDao.getRecordByUserId(NumberUtils.toInt(uId));
            userRole.setRoleId(roleId);
            userRole.setUpdatedBy(userId);
            userRole.setUpdatedTime(DateUtil.getCurrentDate());
            userRoleDao.update(userRole);
        } else if ("1".equals(flag)) {
            User user = userDao.get(uId);
            if (user == null) {
                int errorCode = ExceptionCodeStatusEnum.USER_NOT_FOUND_EXCEPTION.toInt();
                String errorMsg = I18nUtil.getMessage(errorCode, null, "zh_CN");
                throw new BaseAPIException(errorMsg, errorCode);
            }
            user.setIsDeleted(true);
            user.setUpdatedBy(userId);
            user.setUpdatedTime(DateUtil.getCurrentDate());
            userDao.update(user);
        }

        return "操作成功";
    }
}
